package com.iwhalecloud.bss.kite.cucc.service.custview;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.CustViewBaseVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.CustViewVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.PayRelation;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.PayRelationInfoVO;
import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpsCallClient;
import com.iwhalecloud.bss.kite.cucc.common.callclient.constant.CallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalInfConsts;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalAttrHelper;
import com.iwhalecloud.bss.kite.cucc.service.custview.evolve.task.PayRelationTask;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;

import com.ztesoft.bss.common.util.ContextUtil;

/**
 * @ClassName : GetPayRelationTask
 * @Description : 付费关系
 * @Author : xie.zhengjun
 * @Date : 2021/1/22 2:51
 * @deprecated 已停止维护，请勿使用。改进版本解除Callable绑定，干干净净，只专注业务本身。见：{@link PayRelationTask}
 */
public class GetPayRelationTask extends CustViewBaseTask {
    public GetPayRelationTask(Object[] args) {
        super(args);
    }

    @Override
    public CustViewBaseVO call() throws Exception {
        Object[] args = getArgs();
        if (args.length != 4) {
            return null;
        }
        String accNum = (String) args[0];
        Map<String, Object> userDetail = (Map<String, Object>) args[1];
        CustViewVO custViewVO = (CustViewVO) args[2];
        String userCode = (String) args[3];
        PayRelationInfoVO payRelationInfoVO = new PayRelationInfoVO();
        custViewVO.setPayRelation(payRelationInfoVO);
        if (KiteMapUtils.isNotEmpty(userDetail)) {
            Map<String, Object> userInfo = (Map<String, Object>) userDetail.get("USER_INFO");
            if (KiteMapUtils.isNotEmpty(userInfo)) {
                //获取custID
                String custId = String.valueOf(userInfo.get("CUST_ID"));
                String provinceCode = String.valueOf(userInfo.get("PROVINCE_CODE"));
                String eparchyCode = String.valueOf(userInfo.get("EPARCHY_CODE"));

                List<Map<String, Object>> payrelationInfos = (List<Map<String, Object>>) userDetail.get("PAYRELATION_INFOS");
                if (KiteListUtils.isNotEmpty(payrelationInfos)) {
                    List<PayRelation> payRelations = payrelationInfos.stream().map(payrelationInfoMap -> {
                        PayRelation payRelation = new PayRelation(accNum);
                        // 账户标识
                        String acctId = KiteMapUtils.getString(payrelationInfoMap, "ACCT_ID");
                        payRelation.setAcctId(acctId);
                        // 账户名称
                        /*ILocalAccountService accountService = SpringUtil.getBean(ILocalAccountService.class);
                        List<QryCustAccountReq> acctInfoList = acctInfo.getList();
                        String accName = "";
                        if (KiteListUtils.isNotEmpty(acctInfoList)) {
                            accName = Optional.ofNullable(acctInfoList.get(0)
                                .getCustAccount().getPayName()).orElse(accName);
                        }*/
                        String accName = this.listCustAccountInfo(null,
                            null, null,
                            acctId,
                            null, null,
                            null, provinceCode, eparchyCode, userCode,
                            1, 1);
                        payRelation.setAcctName(accName);
                        // 归属省分
                        String regionName = String.join(SymbolConsts.HYPHEN,
                            LocalAttrHelper.getRegionName(KiteMapUtils.getString(payrelationInfoMap, "ACCT_PROVINCE_CODE")),
                            LocalAttrHelper.getRegionName(KiteMapUtils.getString(payrelationInfoMap, "ACCT_EPARCHY_CODE")));
                        payRelation.setRegion(regionName);
                        // 是否默认账户
                        String defaultTag = KiteMapUtils.getString(payrelationInfoMap, "DEFAULT_TAG");
                        payRelation.setDefaultTag(KiteStringUtils.isEqual("1", defaultTag) ? "是" : "否");
                        // 起始账期
                        String startCycId = KiteMapUtils.getString(payrelationInfoMap, "START_CYC_ID");
                        payRelation.setStartDate(formatDate(startCycId));
                        // 终止账期
                        String endCycId = KiteMapUtils.getString(payrelationInfoMap, "END_CYC_ID");
                        payRelation.setEndDate(formatDate(endCycId));
                        // 付费账目名称
                        String payitemCode = KiteMapUtils.getString(payrelationInfoMap, "PAYITEM_CODE");
                        payRelation.setPayitemCode(Optional.ofNullable(AttrValueCache.getAttrValue("2020110805",
                            payitemCode)).map(AttrValue::getAttrValueName).orElse(payitemCode));
                        // 限定方式
                        String limitType = KiteMapUtils.getString(payrelationInfoMap, "LIMIT_TYPE");
                        payRelation.setLimitType(Optional.ofNullable(AttrValueCache.getAttrValue("2020110803",
                            limitType)).map(AttrValue::getAttrValueName).orElse(limitType));
                        // 限定值
                        payRelation.setLimitValue(KiteMapUtils.getString(payrelationInfoMap, "LIMIT_VALUE"));
                        return payRelation;
                    }).collect(Collectors.toList());
                    payRelationInfoVO.setPayRelations(payRelations);
                }
            }
        }
        return payRelationInfoVO;
    }

    private String formatDate(String str) {
        return (KiteStringUtils.isEmpty(str) || str.length() != 6) ?
            str :
            String.join(SymbolConsts.HYPHEN, str.substring(0, 4), str.substring(4, 6));
    }

    private String listCustAccountInfo(String custId, String payName, String acountType,
                                       String acctId, String cbssAcountCode, String provinceAcctId, String payCompactNo, String provinceCode, String eparchyCode,
                                       String userCode, int pageNum, int pageSize) {
        Map<String, Object> uniBssBody = new HashMap<>();
        Map<String, Object> qryCustAccountListReq = new HashMap<>();
        Map<String, String> tcpCont = new HashMap<>();
        //当APP_KEY为Z时,接口增加返回"是否总部直签"
        String headSign = DcPublicCache.getCodea("20201216002", "qryAccountInfo");
        if (KiteStringUtils.equals("T", headSign)) {
            tcpCont.put("APP_KEY", LocalInfConsts.APP_ID_Z);
        } else {
            tcpCont.put("APP_KEY", LocalInfConsts.APP_ID);
        }
        tcpCont.put("TRANSACION_ID", LocalTokenUtil.getTransId());
        qryCustAccountListReq.put("TCP_CONT", tcpCont);

        Map<String, Object> operUserInfo = new HashMap<>();
//        operUserInfo.put("STAFF_ID", "");
        if (KiteStringUtils.isEmpty(userCode)) {
            operUserInfo.put("USER_CODE", KiteStringUtils.valueOf(ContextUtil.getSimpleLoginInfo().getUserCode())); //必填 用户账号
        } else {
            operUserInfo.put("USER_CODE", userCode);
        }
//        operUserInfo.put("ROLE_ID", "");
//        operUserInfo.put("LOGIN_ROLE_AREA_CODE", "");
        qryCustAccountListReq.put("OPER_USER_INFO", operUserInfo);

        qryCustAccountListReq.put("PAGE_SIZE", pageSize); //必填
        qryCustAccountListReq.put("PAGE_NUM", pageNum); //必填
        if (!KiteStringUtils.isBlank(custId)) {
            qryCustAccountListReq.put("CUST_ID", Long.valueOf(custId));
        }
        qryCustAccountListReq.put("ACCT_ID", acctId);
        qryCustAccountListReq.put("ACOUNT_NAME", payName);
        qryCustAccountListReq.put("ACOUNT_TYPE", acountType);
        qryCustAccountListReq.put("CBSS_ACOUNT_CODE", cbssAcountCode);
        qryCustAccountListReq.put("PROVICE_ACOUNT_CODE", provinceAcctId);
        qryCustAccountListReq.put("PAY_COMPACT_NO", payCompactNo);
        qryCustAccountListReq.put("PROVINCE_CODE", provinceCode); //必填
        qryCustAccountListReq.put("EPARCHY_CODE", eparchyCode);
        uniBssBody.put("QRY_CUST_ACCOUNT_LIST_REQ", qryCustAccountListReq);
        String rsp = HttpsCallClient.postStringWithObject(CallClientEnum.QRY_CUSTOMER_ACCTLIST, LocalTokenUtil.getParamMap(uniBssBody), LocalTokenUtil.getHeaderMap());
        PageInfo<Map> custAccountListMap = LocalTokenUtil.checkRespParamAndGetDataListPage(rsp, "QRY_CUST_ACCOUNT_LIST_RSP", Map.class, pageSize, pageNum);
        List<Map> custAccountList = custAccountListMap.getList();
        if (KiteListUtils.isEmpty(custAccountList)) {
            return "";
        }
        Map map = custAccountList.get(0);
        Map<String, Object> custAccount = (Map<String, Object>) map.get("CUST_ACCOUNT");
        String string = KiteMapUtils.getString(custAccount, "PAY_NAME");

        return string;
    }
}
